import { loadEnv } from 'vite'
import fs from 'fs'
import path from 'path'

const customHtmlPlugin = (mode) => {
  const envObj = loadEnv(mode, process.cwd())

  // 读取 package.json
  const pkgPath = path.resolve(process.cwd(), 'package.json')
  let pkgName = ''
  try {
    const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'))
    pkgName = pkg.name || 'MyApp'
  } catch (err) {
    pkgName = 'MyApp'
  }

  return {
    name: 'custom-html-plugin',
    transformIndexHtml(html) {
      return generateHtml(html, envObj, pkgName)
    }
  }
}

const generateHtml = (html, envObj, pkgName) => {
  // 获取页面标题（优先.env配置，没有就用 package.json 的 name）
  let title = envObj['VITE_APP_META_TITLE'] || pkgName
  let keywords = envObj['VITE_APP_META_KEYWORDS'] || `${pkgName}, crypto, defi`
  let description = envObj['VITE_APP_META_DESCRIPTION'] || `${pkgName} official web app`
  let platform = envObj['VITE_APP_ENV'] || 'dev'
  let version = `2.0.${+new Date()}`

  return html
    .replace(
      '<head>',
      `
      <head>
      <meta name="keywords" content="${keywords}" /> 
      <meta name="description" content="${description}" />
      <title>${title}</title>
      <meta content="/platform/${platform}/logo.png?${version}" itemprop="image">
      `
    )
    .replace(
      '</head>',
      `
      <meta property="og:image" content="/platform/${platform}/logo_144.png?${version}">
      <meta property="og:title" content="${title}">
      <meta property="og:description" content="${description}">
      <link rel="icon" href="./platform/${platform}/favicon.ico?${version}" type="image/x-icon"/>
      <link rel="bookmark" href="./platform/${platform}/favicon.ico?${version}" type="image/x-icon">
      <link rel="apple-touch-icon-precomposed" href="/platform/${platform}/logo_57.png?${version}"/>
      <link rel="apple-touch-icon-precomposed" sizes="72x72" href="/platform/${platform}/logo_72.png?${version}"/>
      <link rel="apple-touch-icon-precomposed" sizes="120x120" href="/platform/${platform}/logo_120.png?${version}"/>
      <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/platform/${platform}/logo_144.png?${version}"/>

      <script>
        Object.defineProperty(window, '_APP_VERSION', {
          value: '${version}',
          writable: false,
          configurable: false
        });
        function addLink(rel, href) {
          const domLink = document.createElement('link');
          domLink.rel = rel;
          domLink.href = href;
          document.head.appendChild(domLink);
        }
        function addMeta(name, content) {
          const domMeta = document.createElement('meta');
          domMeta.name = name;
          domMeta.content = content;
          document.head.appendChild(domMeta);
        }
        [
          { name: 'copyright', content: \`© \${new Date().getFullYear()} \${location.host}\` },
        ].forEach((elem) => addMeta(elem.name, elem.content));
        [
          { rel: 'dns-prefetch', href: \`//api.\${location.host}\` },
          { rel: 'preconnect', href: \`//api.\${location.host}\` }
        ].forEach((elem) => addLink(elem.rel, elem.href));
      </script>
     `.replace(/[\n]+/g, '')
    )
}

export { customHtmlPlugin }
